package com.jwthhealth_pub.wristband.setting.view;

import android.Manifest;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.common.base.BaseActivity;
import com.jwthhealth_pub.common.view.TitleLayout;
import com.jwthhealth_pub.wristband.main.view.WristbandMainActivity;
import com.jwthhealth_pub.wristband.presenter.IWristBandGuideServiePersenter;
import com.jwthhealth_pub.wristband.service.WristBandService;
import com.jwthhealth_pub.wristband.view.adapter.WristBandGuideDevListAdapter;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;
import static com.jwthhealth_pub.wristband.broadcast.ServiceOptReceiver.SERVICE_OPT;

/**
 * 连接管理
 * Created by liuzhen on 2017/12/20.
 */

public class WristBandConnManaActivity extends BaseActivity implements IWristBandGuideServiePersenter.view {

    private final String TAG = makeLogTag(WristBandConnManaActivity.class);

    private static final int BLE_NORMAL = -1;
    private static final int BLE_SEARCH_START = 0;
    private static final int BLE_SEARCH_END = 1;
    private static final int BLE_CONNINTING = 2;
    private static final int BLE_CONNINTED = 3;

    @BindView(R.id.pb_wristband_guide_search)
    ProgressBar pbWristbandGuideSearch;
    @BindView(R.id.btn_wristband_search)
    Button btnWristbandSearch;
    @BindView(R.id.rv_wristbandguide_match_list)
    RecyclerView rvMatchWristbandguideList;
    @BindView(R.id.rv_wristbandguide_unmatch_list)
    RecyclerView rvUnMatchWristbandguideList;
    @BindView(R.id.title_layout)
    TitleLayout titleLayout;

    private WristBandService mWristBandService;

    private List<BluetoothDevice> mMatchDevList, mUnMatchDevList;
    private WristBandGuideDevListAdapter mMatchDevListAdapter, mUnMatchDevListAdapter;
    private boolean isScaning;
    private BlueToothStateReceiver mBlueToothDevicesReceiver;
    private View connedLayout;
    private View connLayout;

    public interface bleConnState {
        void conn();

        void disConn();
    }

    @Override
    protected void title() {
        titleLayout.setOnTitleLayoutListener(new TitleLayout.TitleLayoutListener() {
            @Override
            public void leftclick() {
                finish();
            }

            @Override
            public void leftTextClick() {

            }

            @Override
            public void rightclick() {

            }

            @Override
            public void rightTextClick() {

            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wristband_connmana);
        ButterKnife.bind(this);

        connedLayout = findViewById(R.id.layout_wristband_mana_conned);
        connLayout = findViewById(R.id.layout_page_thi);

        //判断手环是否已经链接
        if (WristBandService.isConn) {
            refreahPage(BLE_CONNINTED);
        } else {
            refreahPage(BLE_NORMAL);
        }

        registBlueTooth();

        if (Build.VERSION.SDK_INT >= 23) {
            Acp.getInstance(this).request(new AcpOptions.Builder()
                    .setPermissions(
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION
                    ).build(), new AcpListener() {
                @Override
                public void onGranted() {
                    if (!isServiceRunning(WristBandService.class.getName())) {
                        mWristBandService = new WristBandService();
                        Intent intent = new Intent(getBaseContext(), WristBandService.class);
                        intent.setPackage(getPackageName());
                        startService(intent);
                    } else {
                        if (mWristBandService == null) {
                            mWristBandService = new WristBandService();
                            Intent intent = new Intent(getBaseContext(), WristBandService.class);
                            intent.setPackage(getPackageName());
                            startService(intent);
                        }
                    }
                }

                @Override
                public void onDenied(List<String> permissions) {
                    Toast.makeText(getBaseContext(), "权限拒绝了", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        } else {
            if (!isServiceRunning(WristBandService.class.getName())) {
                mWristBandService = new WristBandService();
                startService(new Intent(getBaseContext(), WristBandService.class));
            } else {
                if (mWristBandService == null) {
                    mWristBandService = new WristBandService();
                    startService(new Intent(getBaseContext(), WristBandService.class));
                }
            }
        }
    }

    @Override
    public void refreahPage(int type) {
        switch (type) {
            case BLE_NORMAL:
                setToptitle(BLE_NORMAL);
                connLayout.setVisibility(View.VISIBLE);
                connedLayout.setVisibility(View.GONE);
                break;
            case BLE_CONNINTED:
                setToptitle(BLE_CONNINTED);
                connedLayout.setVisibility(View.VISIBLE);
                connLayout.setVisibility(View.GONE);
                break;
            case BLE_SEARCH_START:
                setToptitle(BLE_SEARCH_START);
                showLoadProgresbar();
                break;
            case BLE_SEARCH_END:
                btnWristbandSearch.setText(R.string.wristband_ble_research);
                setToptitle(BLE_SEARCH_END);
                missLoadProgressbar();
                break;
            default:
                break;
        }
    }

    @Override
    public void refreshBleDevideList(BluetoothDevice DevName) {

        if (mMatchDevList == null)
            mMatchDevList = new ArrayList<>();

        if (mUnMatchDevList == null)
            mUnMatchDevList = new ArrayList<>();

        int connectState = DevName.getBondState();
        if (connectState == 10) {
            Log.d(TAG, "该设备未配对");
            mUnMatchDevList.add(DevName);

            if (mUnMatchDevListAdapter != null)
                mUnMatchDevListAdapter.notifyDataSetChanged();
            else {
                mUnMatchDevListAdapter = new WristBandGuideDevListAdapter(this, mUnMatchDevList);
                rvUnMatchWristbandguideList.setLayoutManager(new LinearLayoutManager(this));
                rvUnMatchWristbandguideList.setAdapter(mUnMatchDevListAdapter);
            }

        } else if (connectState == 12) {
            Log.d(TAG, "该设备已配对");

            mMatchDevList.add(DevName);

            if (mMatchDevListAdapter != null)
                mMatchDevListAdapter.notifyDataSetChanged();
            else {
                mMatchDevListAdapter = new WristBandGuideDevListAdapter(this, mMatchDevList);
                rvMatchWristbandguideList.setLayoutManager(new LinearLayoutManager(this));
                rvMatchWristbandguideList.setAdapter(mMatchDevListAdapter);
            }

        }
    }

    //连接成功，页面跳转
    @Override
    public void gotoMain() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                missLoadProgressbar();
                Toast.makeText(WristBandConnManaActivity.this, "手环已连接", Toast.LENGTH_SHORT).show();
                new WristbandSettingActivity().finish();

                Intent _intent = new Intent(WristBandConnManaActivity.this, WristbandMainActivity.class);

                startActivity(_intent);

                finish();
            }
        });


    }

    /**
     * 接受广播包括开始、结束扫描，发现设备，
     */
    private void registBlueTooth() {

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mBlueToothDevicesReceiver = new BlueToothStateReceiver();
        registerReceiver(mBlueToothDevicesReceiver, intentFilter);

    }

    private boolean isServiceRunning(final String className) {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> info = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (info == null || info.size() == 0) return false;
        for (ActivityManager.RunningServiceInfo aInfo : info) {
            if (className.equals(aInfo.service.getClassName())) {
                Class<? extends ActivityManager.RunningServiceInfo> service = aInfo.getClass();
                // TODO: 2017/12/21 获取后台正在远行的服务
                return true;
            }
        }
        return false;
    }

    public void connecBleDev(BluetoothDevice bluetoothDevice) {

        if (isScaning) {
            Toast.makeText(this, "扫描尚未结束", Toast.LENGTH_SHORT).show();
        } else {
            mWristBandService.conn(bluetoothDevice, new bleConnState() {
                @Override
                public void conn() {
                    gotoMain();
                }

                @Override
                public void disConn() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO: 2018/1/4 手环断开后，无法在此处更新页面
                            Toast.makeText(WristBandConnManaActivity.this, "手环已断开", Toast.LENGTH_SHORT).show();
                            setToptitle(BLE_NORMAL);
                            connLayout.setVisibility(View.VISIBLE);
                            connedLayout.setVisibility(View.GONE);

                        }
                    });
                }
            });

            showLoadProgresbar();
        }


//        setToptitle(BLE_CONNINTED);
    }

    private void setToptitle(int state) {
//        switch (state) {
//            case BLE_NORMAL:
//                titleLayout.setTitle("连接管理");
//                break;
//            case BLE_SEARCH_START:
//                titleLayout.setTitle("正在扫描...");
//                break;
//            case BLE_SEARCH_END:
//                titleLayout.setTitle("扫描结束");
//                break;
//            case BLE_CONNINTED:
//                titleLayout.setTitle("手环已连接");
//                break;
//            case BLE_CONNINTING:
//                titleLayout.setTitle("正在连接");
//            default:
//                break;
//        }
    }

    /**
     * 处理蓝牙扫描，找到设备等动作
     */
    private class BlueToothStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //找到设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String foundName = device.getName();
                if (foundName == null) return;

                refreshBleDevideList(device);

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //扫描结束
                isScaning = false;
                refreahPage(BLE_SEARCH_END);
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                //开始扫描
                isScaning = true;
                refreahPage(BLE_SEARCH_START);

            }

        }
    }

    @OnClick({R.id.btn_wristband_search, R.id.btn_wristband_disconn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_wristband_search:
                //搜索手环
                if (isScaning) {
                    Toast.makeText(this, "正在搜索", Toast.LENGTH_SHORT).show();
                } else {
                    if (mMatchDevList == null)
                        mMatchDevList = new ArrayList<>();
                    else
                        mMatchDevList.clear();

                    if (mUnMatchDevListAdapter == null)
                        mUnMatchDevList = new ArrayList<>();
                    else
                        mUnMatchDevList.clear();

                    if (mWristBandService != null)
                        mWristBandService.scan();
                    else {
                        //todo 断开设备后，service如果关闭，此处再次启动服务，出现服务无法启动的情况
                        mWristBandService = new WristBandService();
                        Intent intent = new Intent(getBaseContext(), WristBandService.class);
                        intent.setPackage(getPackageName());
                        startService(intent);

                        //服务停止后，需要再次注册蓝牙广播，否则此时接收不到搜索设备信息
                        registBlueTooth();

                        mWristBandService.scan();
                    }
                }
                break;
            case R.id.btn_wristband_disconn:
                // 断开连接
                Intent intent = new Intent();
                intent.setAction(SERVICE_OPT);
                sendBroadcast(intent);

                connLayout.setVisibility(View.VISIBLE);
                connedLayout.setVisibility(View.GONE);

                isScaning = false;

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBlueToothDevicesReceiver != null)
            unregisterReceiver(mBlueToothDevicesReceiver);
    }
}
